<script lang="ts" setup>
import { useVbenModal } from '@vben/common-ui';

import { message, Tag, TreeSelect } from 'ant-design-vue';
import { $t } from '@vben/locales';
import {
  putAdminRolesApiAuthorize,
  putAdminRolesAuthorize,
} from '#/api/admin/roles';

const checkedKeys: any = ref([]);
const treeData = ref([]);
const SHOW_ALL = TreeSelect.SHOW_ALL;
const id = ref();
const type = ref('menus');
const [Modal, modalApi] = useVbenModal({
  onConfirm: async () => {
    const ids = checkedKeys.value.map((item: any) => item.value);
    if (type.value === 'menus') {
      const { msg } = await putAdminRolesAuthorize(id.value, { ids });
      message.success(msg);
    } else {
      const ids: number[] = checkedKeys.value.filter(
        (item: any): item is number => typeof item === 'number',
      );
      const { msg } = await putAdminRolesApiAuthorize(id.value, {
        ids,
        role_id: id.value,
      });
      message.success(msg);
    }

    modalApi.close();
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const values: any = modalApi.getData();
      checkedKeys.value = values.checkedIds;
      treeData.value = values.menusTree;
      id.value = values.id;
      type.value = values.type;
    }
  },
});
</script>
<template>
  <Modal class="w-3/5">
    <TreeSelect
      v-model:value="checkedKeys"
      :field-names="{ children: 'children', label: 'name', value: 'id' }"
      :max-tag-count="1"
      :show-checked-strategy="SHOW_ALL"
      :tree-check-strictly="type === 'menus' ? true : false"
      :tree-data="treeData"
      :placeholder="$t('admin.pleaseSelectPermission')"
      style="width: 100%"
      tree-checkable
      tree-node-filter-prop="name"
    >
      <template #title="{ name, app, controller, action, url, remark }">
        <span class="mr-5">
          {{ name }}
        </span>
        <Tag v-if="type === 'menus'" color="success">
          {{ `${app}/${controller}/${action}` }}
        </Tag>
        <template v-else>
          <Tag color="success">
            {{ url }}
          </Tag>
          <span class="ml-5">
            {{ remark }}
          </span>
        </template>
      </template>
    </TreeSelect>
  </Modal>
</template>
